angular.module('imsApp').controller('mainController', ['$scope', '$rootScope', '$state', 'PermissionCodeManager', '$uibModal', 'AuthManager', function ($scope, $rootScope, $state, PermissionCodeManager, $uibModal, AuthManager) {

    $scope.$state = $state;
    $scope.userInfo = JSON.parse(localStorage.getItem('userInfo'));

    PermissionCodeManager.menuItem().then(function (result) {
        if ($scope.userInfo.userRole == "ims_admin") {
            $scope.meunItems = result.admin;

        } else if ($scope.userInfo.userRole == "advertiser_admin") {
            $scope.meunItems = result.ad;

        } else {
            $scope.meunItems = result.channel;
        }
        $scope.menuSelect = angular.copy($scope.meunItems[0])
        $rootScope.$on('$stateChangeSuccess',
            function (event, toState, toParams, fromState, fromParams) {
                $scope.meunItems.forEach(function (meun) {
                    meun.items.forEach(function (item1) {
                        if (toState.name.indexOf(item1['sref']) > -1) {
                            $scope.menuSelect = meun;

                        } else {
                            item1.items.forEach(function (item) {
                                if (toState.name.indexOf(item['sref']) > -1) {
                                    $scope.menuSelect = meun;
                                    item1.open = true;
                                }

                            })
                        }
                    })
                })

            }
        )
    })
    PermissionCodeManager.codeTable().then(function (result) {
        localStorage.setItem("codeTable", JSON.stringify(result))
        $scope.table = JSON.parse(localStorage.getItem('codeTable'));

    })

    $scope.menuTitleClick = function (item) {
        if (item.sref) {
            $state.go(item.sref, {}, {inherit: false})
        }

    }

    $scope.menuClick = function (menu, index) {

        $scope.menuSelect = menu;
        if ($scope.close) {
            $scope.close = false;
        }
    }


    $scope.resetPasswordModal = function () {
        var modalInstance = $uibModal.open({
            animation: true,
            size: 'normal',
            openedClass: "modal-open-normal",
            templateUrl: 'reset-password.html',
            controller: 'resetPasswordCtrl',
            resolve: {
                user: {}
            }
        })

    }


    $scope.signOut = function () {
        AuthManager.loginOut({token: $scope.userInfo.token}).then(function (result) {
            if (result.data.c == "s") {
                window.location = 'http://' + window.location.host;
            }
        })
    }


}])

